const {User} = require('../models')
const {SECRET} = require('../config/config')
const { v4: uuidv4 } = require('uuid');
// jwt设置token
let jwt = require('jsonwebtoken')
const {StatusEnum} = require("../enum/status.enum");
const {userRegisterError, updatePwdError} = require("../enum/err.type.enum");
const {UserService} = require("../service/user.service");
// 用户登录
const loginCtl = async (ctx) => {
    let {userName, userPwd} = ctx.request.body
    await User.findOne({userName}).then(res => {
        ctx.status = 200;
        if (res) {
            let token = jwt.sign({
                username:userName,
                userId:res.userId
            },SECRET,{
                expiresIn: '3h'
            })
            ctx.body = {
                code: StatusEnum.successStatus,
                data: token,
                msg: '登录成功'
            }
        } else {
            ctx.body = {
                code: StatusEnum.errorStatus,
                msg: '登录失败,用户名或密码错误'
            }
        }
    }).catch(err => {
        ctx.status = 500;
        ctx.body = {
            code: StatusEnum.netErrorStatus,
            msg: '登录异常'
        }
    })
}
const registerCtl = async (ctx) => {
    //接收参数 post
    let {userName, userPwd} = ctx.request.body
    // const findResult = await User.find({
    //     userName: userName
    // });
    // //判断是否存在该用户
    // if (findResult.length > 0) {
    //     //状态码
    //     ctx.status = 200;
    //     ctx.body = {
    //         status: StatusEnum.errorStatus,
    //         data: {
    //             userId: findResult[0].userId
    //         },
    //         message: "用户名已经被占用"
    //     }
    // } else {
        //存储到数据库
        const newUser = new User({
            userId: uuidv4(),
            userName,
            userPwd
        })
        //返回给客户端 一定要await 否则会返回Not Found
        await newUser.save().then(user => {
            ctx.status = 200;
            ctx.body = {
                status: StatusEnum.successStatus,
                message: "注册成功",
                data: user
            }
        }).catch(err => {
            ctx.app.emit('error',userRegisterError,ctx)
        })
    // }
}
const verify  = async (ctx) => {
    let token = ctx.header.authorization
    token = token.replace('Bearer ','')
    try{
       let result =  jwt.verify(token,SECRET)
       await User.findOne({_id:result._id}).then(res =>{
           if(res){
               ctx.body = {
                   code:StatusEnum.successStatus,
                   msg:'用户认证成功',
                   data:res
               }
           }else{
            ctx.body = {
                code:StatusEnum.errorStatus,
                msg:'用户认证失败'
            }
           }
       })
    }catch(err) {
        ctx.body = {
            code:StatusEnum.errorStatus,
            msg:'用户认证失败'
        }
    }
}
const modifyPwd  = async (ctx) => {
    const {userPwd} = ctx.request.body;
    const userId = ctx.state.user.userId;
    if(await UserService.updateByUserId({userId, userPwd})){
        ctx.body = {
            code:0,
            msg:'修改密码成功',
            result:''
        }
    }else{
       ctx.app.emit('error',updatePwdError,ctx)
    }
}

const updatePersonal = async ctx =>{
    let user = ctx.request.body;
    await User.updateOne({
            userId:user.userId,
    },
        {
            avatar:user.avatar,
            sex:user.sex,
            userEmail:user.userEmail,
            phone:user.phone,
        }).then(res => {
        if(res.matchedCount>0){
            ctx.body = {
                code:StatusEnum.successStatus,
                msg:'修改成功'
            }
        }else{
            ctx.body = {
                code:StatusEnum.errorStatus,
                msg:'修改失败'
            }
        }
    }).catch(err =>{
        ctx.body = {
            code:StatusEnum.netErrorStatus,
            msg: err
        }
    })
}
module.exports = {
    loginCtl,
    registerCtl,
    modifyPwd,
    verify,
    updatePersonal
}

